package com.lyrcsoft.springcloudnetflixribbondemo.controller;

import com.lyrcsoft.springcloudnetflixribbondemo.services.ClassB;
import com.lyrcsoft.springcloudnetflixribbondemo.services.ClassService;
import com.netflix.loadbalancer.ILoadBalancer;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * Ribbon 测试
 *
 * @author fujc2dev@126.com
 * @date 2024-08-26
 */
@RestController
@RequestMapping("/test")

public class MyOrderTestController implements ApplicationContextAware {

	private ApplicationContext applicationContext;

	@Bean
	public ClassService classService() {
		return new ClassB("fujc2dev");
	}

	@Resource
	private RestTemplate restTemplate;

	@Autowired
	private LoadBalancerClient loadBalancerClient;

	@GetMapping(value = "/orders")
	public Object orders() {
		ClassService bean = this.applicationContext.getBean(ClassService.class);
		// 通过LoadBalancerClient获取一个ServiceInstance实例
		// 其中包含了host、port等信息
		ServiceInstance serviceInstance = loadBalancerClient.choose("crungoo-lte");
		return restTemplate.getForObject(String.format("http://%s:%s/lte/terminal/page",
				serviceInstance.getHost(), serviceInstance.getPort()), Object.class);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;
	}
}
